<?php
namespace app\api\controller\wxapp;

use app\api\controller\Controller;
use app\common\model\Setting;
use app\common\model\User;
use app\common\model\user\PointsLog;
use app\common\model\wxapp\ShareLog;

class Share extends  Controller{

    public function _initialize()
    {
        parent::_initialize();
    }

    public function goShare(){
        
        $user = $this->getUser(false);

        if($user){
            $open_id=input('request.open_id','','trim');

            if(!$open_id){
                return $this->renderError('无OPENID参数');
            }
            $user_id=User::where(['open_id'=>$open_id])->value('user_id');
            if(!$user_id){
                return $this->renderError('无此用户');
            }
            $isExistId=ShareLog::where(['user_id'=>$user->user_id,'open_id'=>$open_id])->value('log_id');

            if($isExistId){
                return $this->renderError('已访问过此用户');
            }
            $store_info=Setting::getItem('store',$this->wxapp_id);
            $condition['user_id']=$user_id;
            $res=User::where($condition)->setInc('points',$store_info['share_score']);
            if($res!==false){
                ShareLog::insert([
                    'user_id' => $user->user_id,
                    'open_id' => $open_id,
                    'create_time'=>time()
                ]);
                PointsLog::insert([
                    'user_id' => $user->user_id,
                    'value' => $store_info['share_score'],
                    'describe' => '分享后访问得积分',
                    'wxapp_id' =>$this->wxapp_id,
                    'create_time'=>time()
                ]);
                return $this->renderSuccess([], '您已获得'.$store_info['share_score'].'点积分');
            } else {
                return $this->renderError('更新积分失败');
            }
        }

    }
}